package com.tangdi.production.mpaychl.controller.third;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.tangdi.production.mpaychl.controller.BaseController;
import com.tangdi.production.mpaychl.service.impl.bncp.BncpServiceImpl;
import com.tangdi.production.mpaychl.service.impl.bncp.util.MD5Util;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.BusinessException;
import com.tangdi.production.mpbase.service.OrderService;
import com.tangdi.production.mpbase.util.MoneyUtils;

@Controller
@RequestMapping("/bncp")
public class BNCPPayController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(BNCPPayController.class);
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value={"/notify-url"},method={RequestMethod.POST})
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response){
		logger.info("bncp异步回调开始");
		
        // 将异步通知中收到的所有参数都存放到map中
        Map<String, String> paramsMap = getRequestParams(request);
        logger.info("异步回调,获取bncp异步返回,参数:{}", paramsMap);
        
        try {
            // 签名
			String encodeStr = "customerid=".concat(paramsMap.get("customerid"))
					.concat("&").concat("status=").concat(paramsMap.get("status"))
					.concat("&").concat("sdpayno=").concat(paramsMap.get("sdpayno"))
					.concat("&").concat("sdorderno=").concat(paramsMap.get("sdorderno"))
					.concat("&").concat("total_fee=").concat(paramsMap.get("total_fee"))
					.concat("&").concat("paytype=").concat(paramsMap.get("paytype"))
					.concat("&").concat(BncpServiceImpl.API_KEY);
        	
			String sign_out = MD5Util.encode(encodeStr.getBytes());
			if (!sign_out.equals(paramsMap.get("sign"))){
				respContent(response, "验签失败");
				return;
			}
            
			// 订单号
			String prdOrdNo = paramsMap.get("sdorderno");
			if(StringUtils.isEmpty(prdOrdNo)){
				throw new BusinessException(ExcepCode.EX900000,"回调订单号为空");
			}
            
			String status = paramsMap.get("status");
			if ("1".equals(status) == false){
				logger.warn("异步通知的订单状态为非成功，不处理,status:{}", status);
				returnSuccess(response);
				return;
			}
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("prdOrdNo", prdOrdNo);
			Map<String,Object> prdOrdMap = orderService.getPrdOrdMap(queryMap);
			
			String ordStatus = (String) prdOrdMap.get("ordStatus");
			if(MsgCT.ORDSTATUS_SUCCESS.equals(ordStatus)){//成功的订单不允许再更新
				logger.warn("订单状态已成功，不允许更新...");
				returnSuccess(response);
				return;
			}
			
			String amount = paramsMap.get("total_fee");
			logger.info("支付订单金额[{}]元", amount);
			
			amount = MoneyUtils.toStrCent(amount);
			if(amount.equals(prdOrdMap.get("txAmt").toString()) == false){
				throw new BusinessException(ExcepCode.EX900000,"支付金额不一致 成功金额[{}] 订单支付金额[{}]",amount, prdOrdMap.get("txAmt").toString());
			}
			
			//原交易大商户编号
			String mchNo = (String)prdOrdMap.get("TMERCID");
			if(StringUtils.isEmpty(mchNo)){
				throw new BusinessException(ExcepCode.EX900000,"原交易商户号不能为空");
			}
			
			//定义回调订单信息Map
			Map<String,Object> orderCallBackMap = new HashMap<String, Object>();
			orderCallBackMap.put("prdOrdNo", prdOrdMap.get("prdOrdNo"));//订单号
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			orderCallBackMap.put("resJson", JSON.toJSONString(paramsMap));
			
			//支付成功
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_SUCCESS);
			
			//调用回调更新订单
			logger.info("通知平台更新订单[{}]",orderCallBackMap);
			orderService.prdPayCallBack(orderCallBackMap);
			
            // 处理成功后，需要返回SUCCESS，通知中心接受到SUCCESS后将不再通知
            returnSuccess(response);
        	
        } catch (Exception e){
        	logger.error("EPAY异步通知失败:{}", e.getMessage(), e);
        }

		logger.info("bncp异步回调完成");
	}
	
    /**
     * 从请求中获取所有的请求参数
     * 
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    protected Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new TreeMap<String, String>();
        Enumeration<String> names = request.getParameterNames();
        
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            
            params.put(name, value);
        }
        
        return params;
    }
}
